# -*- coding: utf-8 -*-
print("""
# File            :  server.py
# Author          :  电科院吴彦祖
# Create Time     :  2025.05.07 17:06:37
# Python Version  :  3.8.10
    ————MAN！What can i say?
""")

import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

# 加密密钥，必须是16、24或32字节
key = b'1234567891234567' 
# 初始化向量，必须是16字节
iv =b'1234567891234567'  

def decrypt_message(encrypted_message):
    iv = encrypted_message[:AES.block_size]
    encrypted = encrypted_message[AES.block_size:]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted = unpad(cipher.decrypt(encrypted), AES.block_size)
    return decrypted.decode('utf-8')

# 新建服务端Socket
#实验数据：172.20.10.9 #一般：localhost
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('172.20.10.9', 8888)
# 绑定
server_socket.bind(address)
# 监听
server_socket.listen(5)
print("开始监听....", address)

# 接受客户端连接
client_socket, address = server_socket.accept()
print("我们收到{}的连接".format(address))

# 接收客户端发送的加密消息
encrypted_message = client_socket.recv(1024)

# 解密消息
decrypted_message = decrypt_message(encrypted_message)
print("客户端说：", decrypted_message)

# 将解密后的内容保存到文件
with open("server_output.txt", "w", encoding="utf-8") as file:
    file.write(decrypted_message)

#反馈
client_socket.send("消息已接收并解密".encode("utf-8"))

# 关闭连接
client_socket.close()
